"""
用户模型
定义用户相关的数据模型
"""
from sqlalchemy import Boolean, Column, Integer, String, DateTime, func
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from backend.app.utils.auth import get_password_hash, verify_password as auth_verify_password

from backend.app.models.base import BaseModel


class User(BaseModel):
    """用户模型"""
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, nullable=False, index=True)
    email = Column(String(100), unique=True, nullable=False, index=True)
    phone = Column(String(20), unique=True, nullable=True)
    password_hash = Column(String(255), nullable=False)
    is_active = Column(Boolean, default=True)  # 用于表示用户状态（活跃/VIP）

    @classmethod
    def get_by_email(cls, db: Session, email: str) -> Optional["User"]:
        """根据邮箱获取用户"""
        return db.query(cls).filter(cls.email == email).first()

    @classmethod
    def get_by_username(cls, db: Session, username: str) -> Optional["User"]:
        """根据用户名获取用户"""
        return db.query(cls).filter(cls.username == username).first()

    @classmethod
    def create(cls, db: Session, email: str, password: str, username: str, **kwargs) -> "User":
        """创建新用户"""
        user = cls(
            email=email,
            username=username,
            password_hash=get_password_hash(password),
            **kwargs
        )
        db.add(user)
        db.commit()
        db.refresh(user)
        return user

    def verify_password(self, password: str) -> bool:
        """验证密码"""
        return auth_verify_password(password, self.password_hash)

    def __repr__(self):
        return f"<User {self.email}>"